package com.cj.core.crypto;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;

import java.util.Base64;

public class RSAUtil {
    /**
     * 生成 RSA 密钥对（默认 2048 位）
     */
    public static RSA getRSA() throws Exception {
        return SecureUtil.rsa();
    }

    /**
     * 获取 Base64 编码的私钥
     */
    public static String getPrivateKey(RSA rsa) {
        return rsa.getPrivateKeyBase64();
    }

    /**
     * 获取 Base64 编码的公钥
     */
    public static String getPublicKey(RSA rsa) {
        return rsa.getPublicKeyBase64();
    }

    // 示例用法
    public static void main(String[] args) throws Exception {
        RSA rsa = getRSA();
        // 获取私钥
        String privateKey = getPrivateKey(rsa);
        System.out.println("Private Key: " + privateKey);
        // 获取公钥
        String publicKey = getPublicKey(rsa);
        System.out.println("Public Key: " + publicKey);

        // 已经生成密钥对
        String privateKeyStr = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAN80r7Y7AvPXN6OFYgYSxEsZz+wTZVTmoOWbB/d1tdiZYIpomiLGC1gC0IAOAGQM8mOQkx75r3eX4eIbe+fRuwZoB6qvjl73tzu4xCAUV7cHiUTWamGfzFE77beg/0dhMQE28bHsikkClQNlry+CfiYwvpYIVMv39LsUb13G1AmxAgMBAAECgYAC5vdyB+OtPnzkk39iJuNfOrmNS662CJcYtEuXwDO06KQTvRVkNKLZ9PgUANcMLuBbZnMlfUQE8e2X0rzUHpIWT29nQBpgU6QZIjYR1OS5i2XEWTMwk3MdOvoBXz1ye0QFkcnOZvGTPNVXR/3276AKymOdaYSAVjAES6QfiD9SkQJBAPYvqRSpVq7IVnN8jyqhdCPDsVBJKJ7IpNZNk3qGBm3WmIexWvKGg2SQWizx33laupM5IwX+xYd4Hd+345xPeKkCQQDoGoKmg7vhj58axpbfv20SBsKofc2FICSBKPhGCeoscL96zo6DQVyypgTojbNuZRzTXd7A51sK9rCnBq+jWwXJAkBg5rmizFS2T1zX8DtaCFryiOCOPX2jok5fnAFkxMRbD5DSOFkYBSJKvxb/geT4m2G8+Uxz26hcfkcj+/m3WQChAkEAgmER7xOk4Ina6CGR8tIHJM8jXZ59akCqANvQyxcasigLh6KsL1LyDXBw5Wlj16l4zcq3LElJvRjiFpEM7Ihe8QJBAMmit1op+UYp1KhA+dyngnfBp773Q9tg4ABoi4Mjli66cLRKMTQPSbtvISvAh2tDCjToI8d4x2KmGapc7533adM=";
        System.out.println("Private Key: " + privateKeyStr);
        String publicKeyStr = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDfNK+2OwLz1zejhWIGEsRLGc/sE2VU5qDlmwf3dbXYmWCKaJoixgtYAtCADgBkDPJjkJMe+a93l+HiG3vn0bsGaAeqr45e97c7uMQgFFe3B4lE1mphn8xRO+23oP9HYTEBNvGx7IpJApUDZa8vgn4mML6WCFTL9/S7FG9dxtQJsQIDAQAB";
        System.out.println("Public Key: " + publicKeyStr);
        // 构建RSA对象
        RSA resRsa = SecureUtil.rsa(privateKeyStr, publicKeyStr);
        // 加密解密测试
        String message = "Hello, RSA!";
        byte[] encrypted = resRsa.encrypt(message.getBytes(), KeyType.PublicKey);
        System.out.println("Decrypted: " + Base64.getEncoder().encodeToString((encrypted)));
        byte[] decrypted = resRsa.decrypt(encrypted, KeyType.PrivateKey);
        System.out.println("Decrypted: " + new String(decrypted));
    }
}
